<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\personal\controller;

use app\company\service\DataService;
use library\Controller;
use think\Db;


/**工具**/
use wxpay\database\WxPayResults;
use wxpay\database\WxPayUnifiedOrder;
use wxpay\NativePay;
use wxpay\WxPayApi;
use wxpay\WxPayConfig;
use wxpay\Phpqrcode;
use app\common\lib\exception\ApiException;

use EasyWeChat\Factory;

use think\facade\Log;
/**
 * 支付中心管理
 * Class User
 * @package app\worker\controller
 */
class Pay extends Controller
{
    private static $config = [
        'app_id' => 'wxed93066ca98ccfb9',
        'secret' => '667f1a4cf236867c8ad3a36fb4ab8938',
        'key'    => '87e345eecc2fb425c3f39f1b9218a709',
        // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        'response_type' => 'array',
        'mch_id'     => '1330381101',
        'mch_key'    => '87e345eecc2fb425c3f39f1b9218a709',
        'log' => [
            'level' => 'debug',
            'permission' => 0777,
            'file' => RUNTIME_PATH. 'wechat/wxpay.log',
        ],
    ];

    /**
     * 绑定当前数据表
     * @var string
     */
    protected $table = 'commodity';

    /**
     * 支付中心
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $dbconf = $this->getconfig('vister_db');
        $this->title = '支付中心';
        $userinfo = $this->getGuserinfo();
        
        $where1= '';
        if($userinfo['db1']['authorize'] == 2){
            $where1 = ' and type  = 2';
        }
        $where = 'status = 0 and deletetime is null'.$where1;
        $this->_query(Db::connect($dbconf)->table($this->table))->where($where)->page();
            
    }

	/**
     * 支付页面(后台订单)
     * @auth         false
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-10-09T17:25:13+0800
     * @LastTime     2020-10-09T17:25:13+0800
     * @return       [type]                       [description]
     */
	public function pay()
	    {
            $dbconf = $this->getconfig('vister_db');
            $userinfo = $this->getGuserinfo();

            $uid = $userinfo['db2']['id'];
            $uopenid = $userinfo['db2']['openid'];
            if(!$uid && !$uopenid){$this->error('账号未进行绑定');}

            $price = $this->request->param('price');

            $price = $this->curmoney($price);

            $product_id = (int)$this->request->param('product_id');
            $product_info = Db::connect($dbconf)->table('commodity')->where('id = '.$product_id)->find();
            if($product_info['year']!=0){
                $commodity_type = 'Y';
            }elseif ($product_info['month']!=0) {
                 $commodity_type = 'M';
                # code...
            }elseif ($product_info['day']!=0) {
                 $commodity_type = 'D';
                # code...
            }else{
                $this->error('商品信息不存在或已删除');
            }
            $this->assign('vo',$product_info);
            $out_trade_no = makeOrdersn('HL'.$commodity_type);
	        //TODO 进行业务处理
	        //TODO 生成二维码
	        //$product_id = time()+1;
	        $notify = new NativePay();
	        $input = new WxPayUnifiedOrder();
	        $input->setBody("套餐充值");
	        $input->setAttach("xxx");
	        //$input->setOutTradeNo(WxPayConfig::MCHID.date("YmdHis"));
	        $input->setOutTradeNo($out_trade_no);
	        $input->setTotalFee($price);//以分为单位
	        $input->setTimeStart(date("YmdHis"));
	        $input->setTimeExpire(date("YmdHis", time() + 10));
	        $input->setGoodsTag("");
	
	        $input->setNotifyUrl('http://pc.zsicp.com/personal/pay/notify');
	        $input->setTradeType("NATIVE");
	        //$product_id 为商品自定义id 可用作订单ID
	        $input->setProductId($product_id);
	        //$result = $notify->getPayUrl($input);
            $result = WxPayApi::unifiedOrder($input);

	        if (empty($result['code_url'])){
	            $qrCode_url = '';
                
                $this->error('调起支付失败,请稍后再试.');
                exit();
	        }else{
	            $qrCode_url = $result["code_url"];

	        }

            /**
             * 生成订单
             */
            $indata = [
            'userid' => $uid,
            'commodityId' => $product_id,
            'openid' => $uopenid,
            'payType' => 1,
            'status' => 1,
            'amount' => 1,
            'price' => $price/100,
            'createtime' => time(),
            'tradeNo' => $out_trade_no,
            'remark' => '后台订单',
        ];
        $this->assign('tradeNo',$out_trade_no);
        $res = Db::connect($dbconf)->table('commodity_orders')->insert($indata);
	    return $this->fetch('form',[
	       'qrCode_url' => $qrCode_url,
	    
        ]);
		
	}

        /**
         * 微信支付 回调逻辑处理
         * @auth         false
         * @throws           hink\Exception
         * @throws           hink\exception\PDOException
         * @HtttpRequest                              get|post
         * @Author       GNLEON
         * @Param
         * @DateTime     2020-10-10T09:13:34+0800
         * @LastTime     2020-10-10T09:13:34+0800
         * @return       [type]                       [description]
         * @remark  以下套餐均为 月付套餐
         */
	    public function notify(){
            $dbconf = $this->getconfig('vister_db');
	        $wxData = file_get_contents("php://input");
            Log::info('后台支付订单测试1');
            Log::info('后台支付订单'.json_encode($wxData));
            Log::info('后台支付订单'.date('Y-m-d H:i:s',time()));
	        //file_put_contents('/tmp/2.txt',$wxData,FILE_APPEND);
	        try{
	            $resultObj = new WxPayResults();
	            $wxData = $resultObj->Init($wxData);
	        }catch (\Exception $e){
                Log::info('后台支付订单'.date('Y-m-d H:i:s',time()).'----回调失败');
	            $resultObj ->setData('return_code','FAIL');
	            $resultObj ->setData('return_msg',$e->getMessage());
	            return $resultObj->toXml();
	        }
	
	        if ($wxData['return_code']==='FAIL'||
	            $wxData['return_code']!== 'SUCCESS'){
	            $resultObj ->setData('return_code','FAIL');
	            $resultObj ->setData('return_msg','error');
	            return $resultObj->toXml();
	        }
	       
            /**回调订单**/
            if($wxData['return_code']=='SUCCESS'){
                //通信状态 ,不代表支付状态
                if($wxData['result_code'] == 'SUCCESS'){
                    Log::info('后台支付订单'.date('Y-m-d H:i:s',time()).'what??????'.$wxData['out_trade_no'].' 支付成功');

                    // $check = 
                    $where =  'tradeNo = "'.$wxData['out_trade_no'].'"';
                    $data = [
                            'status' => 2,
                            // 'expritime' => time()+(30*24*3600),
                            'payTime' => time() 
                    ];

                    $commodity_date_type  = substr($wxData['out_trade_no'],2,1);
                    $action_date = 0;
                    switch ($commodity_date_type) {
                        case 'Y':
                            $data['expritime'] = time()+(365*24*3600);
                            $action_date = 365*24*3600;
                            # code...
                            break;
                        case 'M':
                            $data['expritime'] = time()+(30*24*3600);
                            $action_date = 30*24*3600;
                            # code...
                            break;
                        case 'D':
                            $data['expritime'] = time()+(1*24*3600);
                            $action_date = 1*24*3600;
                            # code...
                            break;
                        default:
                            # code...
                            break;
                    }
                    try{
                        $res = Db::connect($dbconf)->table('commodity_orders')->where($where)->data($data)->update();
                    }catch (\Throwable $th) {
                        Log::info('后台支付订单'.date('Y-m-d H:i:s',time()).'订单数据更新失败'.$wxData['out_trade_no']);
                    }
                    

                    $orderinfo = Db::connect($dbconf)->table('commodity_orders')->where($where)->find();
                    $uinfo = Db::connect($dbconf)->table('view_user')->where('openid = "'.$orderinfo['openid'].'"')->find();

                    //会员信息(表)
                    //会员级别(0游客,1企业(有物业),2物业,3普通企业(无物业))
                    $is_member =  Db::connect($dbconf)->table('store_member')->where('openid = "'.$orderinfo['openid'].'"')->find();
                    switch ($uinfo['roleid']) {
                        case '2':
                            $vip_level = 0;
                            // $vip_level = 1;
                            break;
                        case '8':
                            $vip_level = 0;
                            # code...
                            // $vip_level = 2;
                            break;
                        default:
                            $vip_level = 0;
                            # code...
                            break;
                    }
                    if($is_member){
                        $updata = [
                            // 'vip_date' => date("Y-m-d H:i:s",$data['expritime']),
                            'commodityid' => $orderinfo['commodityId'],
                            'headimg' => $uinfo['headimgurl'],
                            'phone' => $uinfo['mobile'],
                            'vip_level' => $vip_level,
                        ];

                        /**套餐叠加**/
                        if($is_member['commodityid'] == $orderinfo['commodityId']){

                            $updata['vip_date'] = date("Y-m-d H:i:s",strtotime($is_member['vip_date']) + $action_date);
                        }

                    try{
                        Db::connect($dbconf)->table('store_member')->where('openid ="'.$is_member['openid'].'"')->data($updata)->update();
                    }catch (\Throwable $th) {
                        Log::info('后台支付订单'.date('Y-m-d H:i:s',time()).'会员信息更新失败'.$wxData['out_trade_no']);
                    }


                    }else{
                        $inmember_data = [
                            'openid' => $uinfo['openid'],
                            'headimg' => $uinfo['headimgurl'],
                            'nickname' => $uinfo['nickname'],
                            'phone' => $uinfo['mobile'],
                            'username' => $uinfo['name'],
                            'vip_level' => $vip_level,
                            'vip_date' => date("Y-m-d H:i:s",$data['expritime']),
                            'create_at' => date("Y-m-d H:i:s",time()),
                            'commodityid' => $orderinfo['commodityId']

                        ];
                        try{
                           Db::connect($dbconf)->table('store_member')->insert($inmember_data);
                        }catch (\Throwable $th) {
                            Log::info('后台支付订单'.date('Y-m-d H:i:s',time()).'会员新增信息更新失败'.$wxData['out_trade_no']);
                        }
                        

                    }
                    //end member
                }
                //end success pay
            }

            $order = Db::connect($dbconf)->table('commodity_orders')->where($where)->find();
	        if (!$order || $order['status'] == 2){

	                $resultObj ->setData('return_code','SUCCESS');
	                $resultObj ->setData('return_msg','OK');
	                return $resultObj->toXml();
	        }

            Log::info('后台支付订单'.date('Y-m-d H:i:s',time()).'what??????------------回调结束');
	    }
	

 
    //统一下单 调取微信支付接口
 
    public function paymentlive()
    {
        $data = input();
        $volume_info = [
            'title' => $data['title'],
            'price' => $data['price'],
            'paystatus' => 0,
            'orderid' => time() . rand(1000, 9999)
        ];
 
        try { //添加支付记录
            $result = model('records')->insert($volume_info);
        } catch (\Exception $e) {
            return "提交失败~";
        }
        //var_dump($volume_info);
        $this->get_paysign($volume_info);
 
 
    }
 
  
    public function get_paysign($volume_info)
    {
 
 
        vendor('wxpay.WxPayApi');
        vendor('wxpay.WxPayJsApiPay');
        try{
 
            $tools = new \JsApiPay();
            $openId = $tools->GetOpenid();
 
            //②、统一下单
            $input = new \WxPayUnifiedOrder();
            $input->SetBody("test");
            $input->SetAttach("test");
            $input->SetOut_trade_no("sdkphp".date("YmdHis"));
            $input->SetTotal_fee("1");
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("test");
            $input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openId);
            $config = new WxPayConfig();
            $order = WxPayApi::unifiedOrder($config, $input);
 
            $jsApiParameters = $tools->GetJsApiParameters($order);
 
            //获取共享收货地址js函数参数
            $editAddress = $tools->GetEditAddressParameters();
            $data =[
                'jsApiParameters'=>$jsApiParameters,
                'editAddress'=>$editAddress,
            ];
            return $data;
        } catch(Exception $e) {
            //
            return "提交失败~";
        }
 
    }

	
	 public function wxpay()
    {
        $params = [
            'body' => '支付测试',
            'out_trade_no' => mt_rand().time(),
            'total_fee' => 1,
            'product_id' => time(),
        ];
        //db('order')->insert($params);
        $result = \wxpay1\NativePay::getPayImage($params);
        echo $result;
    }
	
	 // 订单查询
    public function query()
    {
        $out_trade_no = '290000985120170917160005';
        $result = \wxpay\Query::exec($out_trade_no);
        halt($result);
    }
 
    // 退款
    public function refund()
    {
        $params = [
            'out_trade_no' => '290000985120170917160005',
            'total_fee' => 1,
            'refund_fee' => 1,
            'out_refund_no' => time()
        ];
        $result = \wxpay\Refund::exec($params);
        halt($result);
    }
 
    // 退款查询
    public function refundquery()
    {
        $order_no = '290000985120170917160005';
        $result = \wxpay\RefundQuery::exec($order_no);
        halt($result);
    }
 
    // 下载对账单
    public function download()
    {
        $result = \wxpay\DownloadBill::exec('20170923');
        echo($result);
    }
 
    // 通知测试
    // public function notify()
    // {
    //     $notify = new \wxpay\Notify();
    //     $notify->Handle();
    // }
	
    // 扫码支付 生成二维码后转换成图片二维码
    public function qrcodeUrl()
    {
    	require '../extend/wxpay/Phpqrcode.php';//二维码
			$url = urldecode(input('data'));
			if(substr($url, 0, 6) == "weixin"){
		         $qrcode_tools = new \QRcode();
		         echo $qrcode_tools->png($url);
				//QRcode::png($url);
			}else{
				 echo header('HTTP/1.1 404 Not Found');
			}
    }


    /**
     * 权限表单数据处理
     * @param array $data 表单数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$data)
    {
        // if ($this->request->isGet()) {
        //     $where = ['status' => '1', 'is_deleted' => '0'];
        //     $this->auths = Db::name('company_user_auth')->where($where)->order('sort desc,id desc')->select();
        //     array_unshift($this->auths, ['id' => '0', 'title' => '所有权限', 'path' => '/']);
        //     $data['svn_authorize'] = isset($data['svn_authorize']) ? explode(',', $data['svn_authorize']) : [];
        // } else {
        //     if (isset($data['svn_authorize']) && is_array($data['svn_authorize'])) {
        //         $data['svn_authorize'] = join(',', $data['svn_authorize']);
        //     } else {
        //         $data['svn_authorize'] = '';
        //     }
            // $macs = [];
            // foreach (explode(PHP_EOL, preg_replace("/\s+/", PHP_EOL, trim($data['mobile_macs']))) as $mac) {
            //     if (DataService::applyMacValue($mac)) $macs[] = $mac;
            // }
            // $data['mobile_macs'] = join(PHP_EOL, array_unique($macs));
        // }
    }

    /**
     * 元转分  传入字符串价格 必须-0.00格式
     * @Author      GNLEON
     * @HttpRequest                                                        get|post
     * @Param                                     -
     * @DateTime    2020-10-11
     * @LastTime                                  2020-10-11
     * @copyright   [copyright]
     * @license     [license]
     * @param       [type]                        $price     [description]
     * @return      [type]                                   [description]
     */
    public static  function curmoney($price){
        $price_arr = explode(".", $price);
        $price_arr_last = str_split($price_arr[1]);

        return $price_arr[0]*100 + $price_arr_last[0]*10 + $price_arr_last[1]; 
    }

    /**
     * 手机支付页面
     * @auth         false
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-10-26T13:48:34+0800
     * @LastTime     2020-10-26T13:48:34+0800
     * @return       [type]                       [description]
     */
    public function mobilepay(){
        if($this->request->isPost()){
            $dbconf = $this->getconfig('vister_db');
            $order_no = $this->request->param('order_no');
    
            $where = 'tradeNo = "'.$order_no.'"';
            $res = DB::connect($dbconf)->table('view_commodity_orders')->where($where)->find();
            if(!$res){$this->error('FAILD error commodity');} 
        }
        $this->fetch();

    }

}
